import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/my/my_collection_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/server/api/user_api.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/widgets/loading/no_data_widget.dart';

import 'package:ball_lion/widgets/base/wqs_text.dart';

class MyCollectionPage extends StatefulWidget {
  const MyCollectionPage({super.key});

  @override
  State<MyCollectionPage> createState() => _MyCollectionPageState();
}

class _MyCollectionPageState extends State<MyCollectionPage>
    with TickerProviderStateMixin {
  List<String> tabs = ['全部', '文章', '帖子', '视频'];
  late TabController tabC;

  @override
  void initState() {
    super.initState();
    tabC = TabController(length: 4, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Styles.appBar(title: QsText('收藏')),
      body: Column(children: [
        SizedBox(
            height: 40,
            width: double.infinity,
            child: Styles.tabbar(
              tabs: tabs.map((e) => QsText(e)).toList(),
              // isScrollable: true,
              controller: tabC,
            )
            // labelPadding: EdgeInsets.symmetric(horizontal: 12)),
            ),
        Expanded(
            child: TabBarView(
                controller: tabC,
                children: List.generate(
                    tabs.length, (index) => MyCollectionList(index))))
      ]),
    );
  }
}

class MyCollectionList extends StatefulWidget {
  final int type;
  const MyCollectionList(this.type, {super.key});

  @override
  State<MyCollectionList> createState() => _MyCollectionListState();
}

class _MyCollectionListState extends State<MyCollectionList> {
  int page = 1;
  int pageSize = 20;
  List<MyCollectionEntity>? list;
  EasyRefreshController refreshC =
      EasyRefreshController(controlFinishLoad: true);

  @override
  void initState() {
    super.initState();
    getData();
  }

  getData() async {
    if (page == 1) {
      list = [];
    }
    final response = await UserApi.getMyCollection(widget.type, page, pageSize);
    if (response != null) {
      list!.addAll(response);
      if (page == 1) {
        refreshC.resetFooter();
      } else {
        refreshC.finishLoad(response.length < pageSize
            ? IndicatorResult.noMore
            : IndicatorResult.success);
      }
    }
    update();
  }

  @override
  Widget build(BuildContext context) {
    return list == null
        ? Container()
        : Container(
            color: Colours.greyF2F3F7,
            child: EasyRefresh(
              controller: refreshC,
              onRefresh: () async {
                page = 1;
                await getData();
              },
              onLoad: () async {
                page++;
                await getData();
              },
              child: list!.isEmpty
                  ? NoDataWidget(
                      tip: '暂无收藏',
                      needScroll: true,
                    )
                  : ListView.builder(
                      itemBuilder: (context, index) {
                        return cell(list![index]);
                      },
                      itemCount: list!.length,
                    ),
            ),
          );
  }

  cell(MyCollectionEntity e) {
    return GestureDetector(
      onTap: () {
        if (e.status == 1) {
          final param = jsonEncode(e.href!.params);
          Utils.doJump(param);
        }
      },
      child: Styles.card(
        height: 95,
        padding: EdgeInsets.fromLTRB(12, 12, 12, 12),
        margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
        child: Row(
          children: [
            Expanded(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: QsText(
                    e.status == 1 ? (e.infoTitle ?? '') : '该收藏内容已被删除',
                    maxLines: 2,
                    fontSize: 17,
                  ),
                ),
                SizedBox(width: 8),
                QsText(
                  '收藏于${DateTimeUtils.formatDateString(e.createTime ?? '', 'yyyy/MM/dd')}${e.infoAuthor.hasValue ? " · ${e.infoAuthor}" : ""}',
                  fontSize: 11,
                  color: Colours.grey99,
                ),
              ],
            )),
            if (e.infoImg.hasValue)
              Container(
                decoration:
                    BoxDecoration(borderRadius: BorderRadius.circular(4)),
                clipBehavior: Clip.hardEdge,
                margin: const EdgeInsets.only(left: 12),
                width: 94,
                height: 70,
                child: CachedNetworkImage(
                  imageUrl: e.infoImg ?? "",
                  fit: BoxFit.cover,
                  errorWidget: (context, url, error) =>
                      Container(color: Colors.white),
                  placeholder: ((context, url) =>
                      Container(color: Colors.white)),
                ),
              ).marginOnly(left: 5),
          ],
        ),
      ),
    );
  }
}
